<template>
  <view class="main-box">
    <!-- 支付方式 -->
    <view class="pay_methods">
      <view class="font-32 font-b">选择支付方式</view>
      <radio-group @change="changeRadio">
        <label
          v-for="(item, index) in payMethodList"
          :key="index"
          @click="handlePayItem(item)"
        >
          <view class="pay_methods_item">
            <view class="item_left padding-lr">
              <image :src="item.payIcon"></image>
              <view class="item_name">
                <text>{{ item.payName }}</text>
                <text
                  v-if="
                    bankCardInfo.bankId &&
                    (item.payCode == 'fastpay_ys' ||
                      item.payCode == 'new_fastpay_ys')
                  "
                  >（{{ bankCardInfo.bankName + handleBankAccount() }}）</text
                >
                <text class="payInfo">{{ getRemark(item) }}</text>
              </view>
            </view>
            <view>
              <radio
                activeBackgroundColor="#ECA52B"
                iconColor="#ffffff"
                activeBorderColor="#ffffff"
                :disabled="
                  item.money | isDisable(item.remoteFlag, moneyTotal, item)
                "
                :value="item.payCode"
                :checked="item.payCode == payMethod"
              />
            </view>
          </view>
        </label>
      </radio-group>
      <view class="submit" @tap="handlePay">立即支付</view>
    </view>

    <payPassword ref="payPasswordRef" @pay="handlePay"></payPassword>
    <payCode :show="isShowPayCode" @close="closePayCode" @pay="pay"></payCode>
  </view>
</template>

<script>
import {
  orderPay,
  bankPayVerifyCode,
  orderDetail,
} from "@/common/api/order.js";
import payCode from "@/components/popup/payCode.vue";
import setPayPassword from "@/components/payPassword/setPayPassword.vue";
import payPassword from "@/components/payPassword/payPassword.vue";
export default {
  props: {
    payMethodList: Array,
    orderId: String,
    orderDetail: Object,
    mixedPaymentList: Array, // 混合支付比例
    extend: Object,
    moneyTotal: Number,
  },
  components: {
    payCode,
    setPayPassword,
    payPassword,
  },
  data() {
    return {
      useNoPayPasswordType: [
        "new_alipay_ys",
        "alipay_ys",
        "fastpay_ys",
        "new_fastpay_ys",
        "wechat_ys",
      ],
      background: {
        backgroundColor: "#1D1D20",
      },
      isSufficient: false,
      payInfo: {},
      payMethod: "",
      bankCardInfo: {},
      isShowPayCode: false,
      addData1: "",
    };
  },
  filters: {
    // 支付方式禁止选择问题
    isDisable(val, flag, moneyTotal, methodsData) {
      let bool = true;
      let money = val || 0;
      let orderMoney = moneyTotal || 0;
      if (!flag) {
        if (money - orderMoney >= 0) {
          bool = false;
        }
      } else {
        bool = false;
      }

      let totalNum = uni.getStorageSync("totalNum");
      // 如果支付金额为0，则禁用支付宝、微信、银行卡
      if (
        totalNum == "0.00" &&
        (methodsData.payCode === "wechat_ys" ||
          methodsData.payCode === "new_wechat_ys" ||
          methodsData.payCode === "alipay_ys" ||
          methodsData.payCode === "new_alipay_ys" ||
          methodsData.payCode === "fastpay_ys" ||
          methodsData.payCode === "new_fastpay_ys")
      ) {
        bool = true;
      }
      return bool;
    },
  },
  created() {
    uni.$on("setSelectBankCard", (res) => {
      this.bankCardInfo = res;
    });
    // 不用选择支付方式，直接弹出密码输入(100%抵扣 或者支付金额为0 时走这里)
    uni.$on("allAssetsPay", () => {
      setTimeout(() => {
        this.payMethod = "asset_pay";
        this.$refs.payPasswordRef.show = true;
      }, 200);
    });
  },
  destroyed() {
    uni.$off("setSelectBankCard");
    uni.removeStorageSync("totalNum"); //返回支付之后清除支付方式
    uni.removeStorageSync("skuData"); //返回支付之后清除支付方式
  },
  methods: {
    // pay(code) {
    // 	bankPayVerifyCode({addData1: this.addData1, verCode: code, orderId: this.orderId}).then(res => {
    // 		if(res.code == 200) {
    // 			this.$msg('支付成功')
    // 			setTimeout(()=> {
    // 				if(this.orderDetail.productArea == 6) {
    // 					// 易购券购卡返回易购券
    // 					uni.redirectTo({
    // 						url: '/pages/my/coupon/eBayCoupon'
    // 					})
    // 				} else {
    // 					uni.redirectTo({
    // 						url: '/pages/order/orderList?tabIndex=' + 2
    // 					})
    // 				}
    // 			}, 1000)
    // 		} else {
    // 			this.$msg(res.msg)
    // 		}
    // 	})
    // },
    closePayCode() {
      this.isShowPayCode = false;
    },
    // 点击支付方式
    handlePayItem(item) {
      // this.payMethod =
      if (
        this.payMethod == "fastpay_ys" ||
        this.payMethod == "new_fastpay_ys"
      ) {
        uni.navigateTo({
          url: "/pages/my/bankCard/bankCardList?isSelect=true",
        });
      }
    },
    // 银行卡账户展示
    handleBankAccount() {
      return this.bankCardInfo.bankAccount.substring(
        this.bankCardInfo.bankAccount.length - 4
      );
    },
    // 回显混合支付还需要支付多少钱
    getRemark(data) {
      let str;
      let orderMoney = this.moneyTotal || 0;
      // 选择资产支付(勾选了资产支付才传)
      if (uni.getStorageSync("totalNum")) {
        orderMoney = uni.getStorageSync("totalNum");
      }
      let remoteFlag = data.remoteFlag;
      let money = data.money || 0;
      if (remoteFlag) {
        str = `(需要支付${orderMoney})`;
      } else {
        str = `(剩余${money}需要支付${orderMoney})`;
      }
      return str;
    },
    // 切换支付方式
    changeRadio(e) {
      this.payMethod = e.detail.value;
    },
    // 支付
    handlePay(password = {}) {
      if (!this.payMethod) {
        return this.$msg("请选择支付方式");
      }

      let data = {
        outOrderId: this.orderId,
        payMethod: this.payMethod,
      };

      //支付密码
      // if(!this.useNoPayPasswordType.includes(this.payMethod)){
      // 	if(!password.password){
      // 		this.$refs.payPasswordRef.show = false
      // 		setTimeout(()=>{
      // 			this.$refs.payPasswordRef.show = true
      // 		},200)
      // 			return
      // 	}else {
      // 		data['payCipher'] = password.password
      // 		// this.$refs.payPasswordRef.close()
      // 	}
      // }

      uni.showLoading({
        title: "支付中...",
        mask: true,
      });

      // 银行卡支付(新银行卡+旧银行卡)
      // if(this.payMethod == 'fastpay_ys' || this.payMethod == 'new_fastpay_ys') {
      // 	data.signId = this.bankCardInfo.signId
      // }
      orderPay(data)
        .then((res) => {
          uni.hideLoading();
          if (res.code == 200) {
            uni.removeStorageSync("totalNum"); //支付成功之后清除支付方式
            uni.removeStorageSync("skuData"); //支付成功之后清除支付方式
            if (this.payMethod == "wechat") {
              uni.setStorageSync("payWechat", true);
              uni.showLoading({
                title: "跳转支付中...",
                mask: true,
              });
              setTimeout(() => {
                uni.hideLoading();
              }, 3500);
			  let url = "https://junjingvip.cn:9993/pay.html?url=" + encodeURIComponent(res.data.pay);
			  if(window.sdkManager){  
				window.sdkManager.openHtmlUrl(url);
			  }else{				  
			  window.location.href = url
			  }
            } else if (
              this.payMethod == "alipay" ||
              this.payMethod == "new_alipay"
            ) {
              uni.setStorageSync("payAlipay", true);
              let data = res.data.pay; //返回的form表单
              uni.showLoading({
                title: "跳转支付中...",
                mask: true,
              });
              setTimeout(() => {
                uni.hideLoading();
              }, 3500);
              const div = document.createElement("div");
              div.innerHTML = data;
              document.body.appendChild(div);
              document.forms[0].submit();
            } else if (
              this.payMethod == "fastpay_ys" ||
              this.payMethod == "new_fastpay_ys"
            ) {
              this.addData1 = res.data || "";
              this.isShowPayCode = true;
            } else {
              this.$msg("支付成功");
              setTimeout(() => {
                uni.redirectTo({
                  url: "/pages/order/orderList?tabIndex=" + 2,
                });
              }, 1000);
            }
          } else {
            this.$msg(res.msg);
          }
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.main-box {
  .pay_methods {
    font-size: 28rpx;
    background-color: #fff;
    border-radius: 14rpx;

    .pay_methods_item {
      margin-top: 30rpx;
      display: flex;
      justify-content: space-between;

      .item_left {
        display: flex;
        align-items: center;

        .item_name {
          font-size: 30rpx;
        }

        image {
          width: 60rpx;
          height: 60rpx;
          margin-right: 10rpx;
        }
      }
    }

    .submit {
      width: 612rpx;
      height: 88rpx;
      background: #eca52b;
      border-radius: 20rpx;
      font-size: 36rpx;
      color: #ffffff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 80rpx auto;
    }
  }
}
.payInfo {
  color: #eca52b;
  font-size: 28rpx;
  font-weight: bold;
}
</style>
